import { useGlobalStore } from '@/store'
import useInteraction from './useInteraction'

interface WriteFileConfig {
  content: any
  root: string
  filename: string
  useExport?: boolean
}
const { treePath } = useGlobalStore()

const isWithExt = (filename: string) => /\.\w+$/.test(filename)
/**
 * @description 写入文件
 */
export const useWriteFile = async (config: WriteFileConfig, minWait = 500) => {
  return useInteraction<{ error: string }>({
    type: 'file',
    eventName: 'write-file',
    data: {
      content: JSON.stringify(config.content, null, 2),
      root: config.root ?? treePath,
      filename: isWithExt(config.filename) ? config.filename : `${config.filename}.ts`,
      useExport: config.useExport ?? true
    },
    minWait
  })
}

interface FileExistConfig {
  path: string
  returnText?: boolean
}
/**
 * @description 查询某个文件是否存在, 同时返回文件内容
 */
export const usePathExist = (config: FileExistConfig) => {
  return useInteraction<{ isExist: boolean; content: string }>({
    type: 'file',
    eventName: 'check-is-exist',
    data: {
      path: config.path,
      returnText: config.returnText ?? false
    }
  })
}

interface CreateDirConfig {
  paths: string | string[]
  root: string
}
/**
 * @description 创建文件夹
 */
export const useCreateDirectory = async (config: CreateDirConfig) => {
  return useInteraction<{ error: string }>({
    type: 'file',
    eventName: 'create-directory',
    data: {
      paths: config.paths,
      root: config.root
    }
  })
}

export const useSelectPath = () => {
  return useInteraction<{ path: string }>({
    type: 'file',
    eventName: 'select-path'
  })
}
